package com.vgooo.client;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.client.vchannel.player.VideoPlayerActivity;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.DebugTools;
import com.vgooo.util.Loading;
import com.vgooo.util.SimpleLoading;
import com.vgooo.util.SimpleLoading.Progress;
import com.vgooo.util.UmengUtils;

public class VGActivity extends FragmentActivity {

	public final static int LOADER_SUCCESS = 0xfff;
	public final static int LOADER_FAIL = LOADER_SUCCESS + 1;

	public Context context = this;
	public VGActivity cparent = this;

	protected boolean isFirst = true;

	protected boolean needNewLoading = false;

	// protected static View blank ;
	protected View detailVeiw;
	protected LayoutInflater inflater;

//	protected Progress progress;
	protected Progress progress;

	private boolean loadSuccesss = false;

	public boolean needNewProgress = false;

	// VGInterface vgInterface ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		inflater = getLayoutInflater();
		// blank = inflater.inflate(R.layout.blank, null);
		DebugTools.log(getClass().getSimpleName(), "---onCreate---");
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		DebugTools.log(getClass().getSimpleName(), "---onStart---");
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		DebugTools.log(getClass().getSimpleName(), "---onRestart---");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
		// 清除软引用中图片缓存缓存
		BitmapUtils.cleanCache();
		DebugTools.log(getClass().getSimpleName(), "---onResume---");
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
		// 清除软引用中图片缓存缓存
		BitmapUtils.cleanCache();
		DebugTools.log(getClass().getSimpleName(), "---onPause---");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		DebugTools.log(getClass().getSimpleName(), "---onStop---");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		DebugTools.log(getClass().getSimpleName(), "---onDestroy---");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if(null!=progress){
				progress.cancel();
			}
			DebugTools.log(getClass().getSimpleName(), "你按下了返回键。。。。");
			ViewLayout.setViewBack();
		}
		return true;
	}

	public void back() {
		ViewLayout.setViewBack();
	}

	/**
	 * 初始化视图
	 */
	public void initView() {
	};

	/**
	 * 加载视图
	 * 
	 * @throws IOException
	 * @throws Exception
	 */
	public void setupView() throws RuntimeException {
	};

	/**
	 * 添加监听器
	 */
	public void addListener() {
	};

	/**
	 * 刷新视图
	 * 
	 * @throws Exception
	 */
	public void flashView() throws Exception {
	};

	/**
	 * 获取数据
	 * 
	 * @throws Exception
	 */
	public void getData() throws RuntimeException {
	};

	/**
	 * 控件的点击事件
	 * 
	 * @param v
	 * @throws Exception
	 */
	public void doClick(View v) {
	};

	/**
	 * 清空界面正在显示的数据
	 */
	public void clearView() {
	};

	public void init() {
		new AsyncTask<String, String, String>() {

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				if (VGApplication.isDebug) {
					getData();
				} else {
					try {
						getData();
						loadSuccesss = true;
					} catch (Exception e) {
						loadSuccesss = false;
						publishProgress(e.toString());
						UmengUtils.onError(context, e.toString());
					}
				}
				return null;
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				if (progress == null || needNewProgress) {
					progress = SimpleLoading.startProgress(cparent);
				} else {
					progress.start();
				}
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				progress.cancel();
				if (VGApplication.isDebug) {
					setupView();
				} else {
					if (loadSuccesss) {
						try {
							setupView();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							publishProgress(e.toString());
							e.printStackTrace();
						}
					} else {
						Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT)
								.show();
					}
				}
			}

			@Override
			protected void onProgressUpdate(String... values) {
				// TODO Auto-generated method stub
				super.onProgressUpdate(values);
				String value = values[0];
				UmengUtils.onError(context, value);
				if (VGApplication.isDebug) {
					throw new RuntimeException(value);
				}
				// throw new RuntimeException(value);
			}

		}.execute("");
	}
	
	/* 通用功能 */
	
	
	private static final int IMAGE_ZOOM = 0xfba ;
	private static final int ALBUMS_SHOW = IMAGE_ZOOM+1 ;
	private static final int PLAY_VIDEO = ALBUMS_SHOW+1 ;
	private  final WebView videoWebView = new WebView(Main.activity);
	private  Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int what = msg.what ;
			Bundle bundle = (Bundle) msg.obj;
			switch (what) {
			case IMAGE_ZOOM:
				Main.imageZoomIntent.putExtra("link", bundle.getString("imageUrl"));
				ViewLayout.setViewPre(true, "图片放大", ViewLayout.TAB_TAG_IMAGEZOOM,cparent);
				break;
			case ALBUMS_SHOW:
				String id = bundle.getString("id");
				String image_id = bundle.getString("image_id");
				Main.moblieAlbumIntent.putExtra("id", id);
				Main.moblieAlbumIntent.putExtra("image_id",image_id);
				ViewLayout.setViewPre(true, "产品图赏",ViewLayout.TAB_TAG_MOBILE_ALBUM,cparent);
				break;
				
			case PLAY_VIDEO :
				if(null==progress){
					progress = SimpleLoading.startProgress(cparent) ;
				}else{
					progress.start();
				}
				String url = bundle.getString("url") ;
				WebSettings set = videoWebView.getSettings() ;
				set.setPluginsEnabled(false);
				videoWebView.setWebViewClient(new WebViewClient(){
					public boolean shouldOverrideUrlLoading(WebView view, String url) {
						if(!progress.isLoading()){
							progress.cancel() ;
							return true ;
						}
						if(url.endsWith(".3gp")||url.endsWith(".mp4")||url.endsWith(".3GP")||url.endsWith(".MP4")){
							Intent intent = new Intent(Main.activity, VideoPlayerActivity.class);
							intent.setAction(Intent.ACTION_VIEW) ;
							Uri uri = Uri.parse(url);
							intent.setDataAndType(uri, "video/*") ;
							if(!progress.isLoading()){
								progress.cancel() ;
								return true ;
							}
							Main.activity.startActivity(intent);
							if(progress!=null){
								progress.cancel() ;
							}
						}else{
							videoWebView.loadUrl(url);
						}
						return true;};
				});
				videoWebView.loadUrl(url);
				break ;

			default:
				break;
			}
		}
	};
	
	/* 点击图片放大 */
	public void imageZoom(String imageUrl)
	{
		if(null==imageUrl||"".equals(imageUrl.trim())){
			return ;
		}
		Message msg = Message.obtain();
		Bundle bundle = new Bundle() ;
		bundle.putString("imageUrl", imageUrl);
		msg.obj = bundle;
		msg.what = IMAGE_ZOOM ;
		
		handler.sendMessage(msg);
	}
	
	
	/* 点击图片放大 */
	
	/* 点击图片查看图赏*/
	/**
	 * 
	 * @param id
	 * @param image_nickname
	 */
	public void albumShow(String image_prod_id ,String image_id){
		if(null==image_prod_id||"".equals(image_prod_id.trim())||null==image_id||"".equals(image_id.trim())){
			return ;
		}
		Message msg =  Message.obtain();
		Bundle bundle = new Bundle() ;
		bundle.putString("id", image_prod_id);
		bundle.putString("image_id", image_id);
		msg.obj = bundle;
		msg.what = ALBUMS_SHOW;
		handler.sendMessage(msg);
	}
	
	/* 点击图片查看图赏*/
	
	
	/* 播放视频*/
	public void playVideo(String url){
		System.out.println("  playVideo : " + url);
		if(null==url||"".equalsIgnoreCase(url)||! url.startsWith("http://")){
			return ;
		}
		Message msg = Message.obtain();
		Bundle bundle = new Bundle() ;
		bundle.putString("url", url);
		msg.obj = bundle;
		msg.what = PLAY_VIDEO ;
		
		handler.sendMessage(msg);
	}
	/* 播放视频*/
	
	private  void log(String info){
		Log.i(getClass().getSimpleName(), info);
	}
}
